package com.wn.network.utils

import com.blankj.utilcode.util.AppUtils
import com.wn.network.constant.BASE_URL
import com.wn.network.interceptor.HttpLogInterceptor
import com.wn.network.interceptor.LogLevel
import com.wn.network.interceptor.NetworkInterceptor
import com.wn.network.interceptor.PublicParameterInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author: wn
 * @Date: 2025/7/17 17:01
 * @Description: API管理器  -- 非 hilt 的方式 提供 API
 */
object ApiManager {

  private val mRetrofit: Retrofit

  init {
    mRetrofit = Retrofit.Builder()
      .client(initOkHttpClient())
      .baseUrl(BASE_URL)
      .addConverterFactory(GsonConverterFactory.create())
      .build()
  }

  /**
   * 获取 api
   * @param api Class<T>  -- ApiInterface::class.java
   * @return T
   */
  fun <T> create(api: Class<T>): T {
    return mRetrofit.create(api)
  }

  /**
   * 初始化OkHttp
   */
  private fun initOkHttpClient(): OkHttpClient {
    val build = OkHttpClient.Builder()
      .callTimeout(10, TimeUnit.SECONDS) // 完整请求超时时长，从发起到接收返回数据，默认值0s，不限定
      .connectTimeout(12, TimeUnit.SECONDS) // 与服务器建立连接的时长，默认--10s  秒
      .readTimeout(12, TimeUnit.SECONDS) // 读取服务器返回数据的时长  s
      .writeTimeout(12, TimeUnit.SECONDS) // 向服务器写入数据的时长，默认--10s
    // 添加参数拦截器
    build.addInterceptor(NetworkInterceptor())
    build.addInterceptor(PublicParameterInterceptor())
    build.addInterceptor(HttpLogInterceptor().apply {
      logTag("<wn--Retrofit>")
      if (AppUtils.isAppDebug())
        logLevel(LogLevel.BODY)
      else
        logLevel(LogLevel.BASIC)
    })
    return build.build()
  }
}